package cn.itlaobing.web.utils;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ImgUploadUtil {

    @RequestMapping(value = "imgUpload")
    public void imgUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = true) MultipartFile file) {
        JSONObject json = new JSONObject();
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //键
        String result="result";
        String[] type = file.getContentType().split("/");
        PrintWriter out = null;
        // 物理地址
        String path = request.getServletContext().getRealPath("/uploadimg");
        //文件名
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String imgname = formatter.format(date);
        try {
            file.transferTo(new File(path+"/"+imgname+"."+type[type.length-1]));
            //图片名称
            String img=imgname+"."+type[type.length-1];
            //放到map集合中
            json.put(result,img);
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将json数据传回客户端
        out.print(json);
        out.flush();
        out.close();
    }
}
